package com.zrrd.blog.wnb.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.arronlong.httpclientutil.HttpClientUtil;
import com.arronlong.httpclientutil.common.HttpConfig;
import com.arronlong.httpclientutil.common.HttpHeader;
import com.arronlong.httpclientutil.exception.HttpProcessException;
import com.zrrd.blog.util.base.Result;
import com.zrrd.blog.util.enums.ResultEnum;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AuthService {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /**
     * 通过刷新令牌获取新的令牌及下次的刷新令牌，手动封装成Result对象
     * @param hearder 请求头 ：客户端信息 clientId：clientSecret
     * @param refreshToken 刷新令牌
     */
    public Result refreshToken(String hearder,String refreshToken) throws HttpProcessException {
        //采取客户端负载
        ServiceInstance serviceInstance = loadBalancerClient.choose("auth-server");
        if (serviceInstance == null) {
            return Result.error("未找到有效的认证服务");
        }
        //请求刷新令牌url
        String refreshTokenUrl = serviceInstance.getUri().toString() + "/auth/oauth/token";
        //封装刷新令牌请求参数
        Map<String, Object> map = new HashMap<>();
        map.put("grant_type", "refresh_token");
        map.put("refresh_token", refreshToken);
        //构建配置请求参数
        Header[] headers = HttpHeader.custom().contentType(HttpHeader.Headers.APP_FORM_URLENCODED).authorization(hearder).build();
        //请求配置
        HttpConfig config = HttpConfig.custom().headers(headers).url(refreshTokenUrl).map(map);
        //发送请求
        String token = HttpClientUtil.post(config);
        JSONObject jsonObject = JSON.parseObject(token);
        if (StringUtils.isNotEmpty(jsonObject.getString("error"))) {
            return Result.build(ResultEnum.TOKEN_PAST);
        }
        return Result.ok(jsonObject);
    }
}
